package org.example.interceptors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.example.domain.beans.JwtParseInfo;
import org.example.util.FmBackendJwtUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 *   400 参数错误
 *   401 没有登录
 *   403  没有权限
 */

@Component
public class FmBackendJwtTokenInterceptor implements HandlerInterceptor {

    private FmBackendJwtUtils fmBackendJwtUtils;
    private Log log= LogFactory.getLog(FmBackendJwtTokenInterceptor.class);

    public FmBackendJwtTokenInterceptor(FmBackendJwtUtils fmBackendJwtUtils) {
        this.fmBackendJwtUtils = fmBackendJwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //因为浏览器访问时会发送一个options请求，
        if (request.getMethod().equalsIgnoreCase("OPTIONS")){
            response.setStatus(HttpStatus.OK.value());
            return true;
        }

        String authorization = request.getHeader("Authorization");
        if (StringUtils.hasText(authorization)&&authorization.startsWith("Bearer")){
            //抽取token
            String access_token = authorization.replace("Bearer ", "");
            JwtParseInfo jwtParseInfo = fmBackendJwtUtils.validateAccessJwt(access_token);
            switch (jwtParseInfo.getSignatureStatus()){
                case correct:
                    return true;
                case tamper://被篡改了
                    log.info(jwtParseInfo.getClaims()+"##########");
                    response.setStatus(401);
                   return false;
                case expired: //签名过期了
                    //自定义的状态码
                    response.setStatus(586);
                    return false;
            }
            return false;
        }else {
            response.setStatus(401);
            return false;
        }

    }
}

























